package cn.jn.lhm.msm.service.impl;

import cn.jn.lhm.msm.service.MsmService;
import cn.jn.lhm.utils.R;
import cn.jn.lhm.utils.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author LHM
 * @Tips 热爱每一天，奋斗每一天
 * @date 2020/6/10 - 20:10
 */
@Service
public class MsmServiceImpl implements MsmService {


    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean sendMsm(String num) {
        //先宣传redis中是否有值
        String redisCode = redisTemplate.opsForValue().get(num);
        if (!StringUtils.isEmpty(redisCode)) {
            return true;
        }
        //生成四位的随机验证码
        String code = RandomUtil.getFourBitRandom();
        //将验证码发送到阿里云
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        DefaultProfile profile = DefaultProfile.getProfile("default",
                "LTAI4GF8DyH4BsUVUDMpAvkz","ebqpUniiZIllqmFj4bWPgQMLzo1TAu");
        DefaultAcsClient client = new DefaultAcsClient(profile);
        //设置固定的相关的参数
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //设置发送的相关参数
        //接收者手机号
        request.putQueryParameter("PhoneNumbers", num);
        //签名名称
        request.putQueryParameter("SignName","xx学习平台");
        //模板code
        request.putQueryParameter("TemplateCode","SMS_189610869");
        //验证码，需使用json格式的数据
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            if (response.getHttpResponse().isSuccess()){
                //设置5分钟过期
                redisTemplate.opsForValue().set(num, code,5, TimeUnit.MINUTES);
                return true;
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
